package cz.proks.schoolpupilbook.gwt.core.handler;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;

import cz.proks.schoolpupilbook.gwt.core.ResultNotifiable;
import cz.proks.schoolpupilbook.gwt.service.ServiceFactory;
import cz.proks.schoolpupilbook.gwt.service.UserRelationService;
import cz.proks.schoolpupilbook.gwt.widget.common.UserRelationForm;
import cz.proks.schoolpupilbook.gwt.widget.common.UserRelationForm.SubmitEvent;
import cz.proks.schoolpupilbook.shared.domain.User;
import cz.proks.schoolpupilbook.shared.domain.UserRelation;

public class UserRelationFormHandler implements UserRelationForm.SubmitEvent.SubmitEventHandler {
	@Override
	public void onSubmit(SubmitEvent event) {
		UserRelationService userRelationService = ServiceFactory.getUserRelationService();
		UserRelation userRelation = createUserRelation(event);
		
		userRelationService.save(userRelation, new ResultNotifiable<Void>() {
			
			@Override
			public void onSucces(Void object) {
				History.back();
			}
			
			@Override
			public void onError(Throwable t) {
				Window.alert("Failed to save user-relation: " + t.getLocalizedMessage());				
			}
		});
	}
	
	private UserRelation createUserRelation(SubmitEvent event) {
		UserRelation userRelation = new UserRelation();
		User parent = new User();
		User student = new User();
		
		parent.setId(event.getParentId());
		student.setId(event.getStudentId());
		
		userRelation.setId(event.getId());
		userRelation.setParent(parent);
		userRelation.setStudent(student);
		
		return userRelation;
	}
}
